﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.User;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.User
{
    public class AddUserRoelHandler : IRequestHandler<AddUserRoelCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserRoleModel> _urRepository;
        private readonly IMapper _mapper;

        public AddUserRoelHandler(IBaseRepository<UserRoleModel> urRepository, IMapper mapper)
        {
            _urRepository = urRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 用户角色保存
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(AddUserRoelCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int>result =new ApiResult<int>();

            //先删除旧的关联
            var userrole = _urRepository.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
            if (userrole.Any())
            {
                _urRepository.DeleteRange(userrole);
            }

            if (!string.IsNullOrEmpty(request.UserId))
            {
                var list = request.UserId.Split(',').Select(x => Convert.ToInt32(x)).ToList();
                foreach (var item in list)
                {
                    UserRoleModel userRoelModel = new UserRoleModel();
                    userRoelModel.UserId = item;
                    userRoelModel.RoleId = request.RoleId;

                    _urRepository.Add(userRoelModel);
                }
                result.Code = StatusEnum.OK;
                result.Message = "保存成功";
                result.Data = 1;
                return Task.FromResult(result);
            }
            result.Code = StatusEnum.Fail;
            result.Message = "保存失败";
            result.Data = 0;
            return Task.FromResult(result);
        }
    }
}
